<?php

namespace Home\Controller;

use Home\Model\WechatUserModel;
use Think\Controller;
use Home\Service\Crypto\wxBizMsgCrypt;
use Wap\Service\WechatService;

class OpenWxController extends Controller
{
    private $_token = 'esm';
    private $_encodingAesKey = 'wY8pJ0tB3nOZytwVS2xyL3dU2V9NXY7ug3aOARBpX8Z';
    /*private $_appId = 'wx9fee8af7befe3df5';
    private $_appSecret = '1282128572e92b0e91d190b3bf882f02';*/
    private $_appId = 'wxb103d59ce45902a1';
    private $_appSecret = '98e730f1ba6750e1b83448c8c8c67551';

    //用于接收取消授权通知、授权成功通知、授权更新通知，也用于接收ticket，ticket是验证平台方的重要凭据
    public function index()
    {
        $token = $this->_token;
        $encodingAesKey = $this->_encodingAesKey;
        $appId = $this->_appId;
        $pc = new WXBizMsgCrypt();
        $pc->WXBizMsgCrypt($token, $encodingAesKey, $appId);

        $msg_sign = $_GET['msg_signature'];
        $timeStamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $msg = '';
        $postStr = file_get_contents('php://input');

        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($postStr);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);

        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
        if ($errCode == 0) {
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;
            /*$fp = fopen("/var/www/zjdaily/trunk/Public/Uploads/lottery/20180816/1.txt", "a");
            fwrite($fp, $component_verify_ticket . "\r\n");
            fclose($fp);*/
            S("component_verify_ticket", $component_verify_ticket);
            echo "success";
        } else {
            /*$fp = fopen("/var/www/zjdaily/trunk/Public/Uploads/lottery/20180816/3.txt", "a");
            fwrite($fp, $errCode . "\r\n");
            fclose($fp);*/
        }
    }

    //获取第三方平台component_access_token
    private function _getComponentAccessToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
        $post_data = array(
            'component_appid' => $this->_appId,
            'component_appsecret' => $this->_appSecret,
            'component_verify_ticket' => S("component_verify_ticket")
        );
        $post_data = json_encode($post_data);
        $result = $this->_curlPost($url, $post_data);
        echo $result;
        $result = json_decode($result, true);
        $component_access_token = $result["component_access_token"];
        S("component_access_token", $component_access_token, 7200);
    }

    //获取预授权码pre_auth_code
    public function getPreAuthCode()
    {
        $component_access_token = S("component_access_token");
        if (empty($component_access_token)) {
            $this->_getComponentAccessToken();
            $component_access_token = S("component_access_token");
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=';
        $url = $url . $component_access_token;
        $post_data = array(
            'component_appid' => $this->_appId
        );
        $post_data = json_encode($post_data);
        $result = $this->_curlPost($url, $post_data);
        $result = json_decode($result, true);
        $pre_auth_code = $result["pre_auth_code"];
        S("pre_auth_code", $pre_auth_code);//10分钟
        echo $pre_auth_code;
    }

    //授权注册页面扫码地址
    public function register()
    {
        $pre_auth_code = S("pre_auth_code");
        $redirect_uri = C("SITE_URL") . '/Home/OpenWx/code';
        $redirect_uri = urlencode($redirect_uri);
        $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=' . $this->_appId .
            '&pre_auth_code=' . $pre_auth_code . '&redirect_uri=' . $redirect_uri . '&auth_type=1';
        //redirect($url);
        echo "<div style='margin:0 auto;'><h2><a href='{$url}'>授权微信小程序</a></h2></div>";
    }

    //回调url，获得授权码
    public function code()
    {
        $auth_code = $_GET['auth_code'];
        echo $auth_code;
    }

    //通过该URL接收公众号或小程序消息和事件推送，该参数按规则填写（需包含/$APPID$，如www.abc.com/$APPID$/callback），
    //实际接收消息时$APPID$将被替换为公众号或小程序AppId。
    public function message()
    {
        $postStr = file_get_contents('php://input');
        $timeStamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $msg_sign = $_GET['msg_signature'];

        $token = $this->_token;
        $encodingAesKey = $this->_encodingAesKey;
        $appId = $this->_appId;
        $pc = new WXBizMsgCrypt();
        $pc->WXBizMsgCrypt($token, $encodingAesKey, $appId);

        $xml_tree = new \DOMDocument();
        $xml_tree->loadXML($postStr);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');
        $encrypt = $array_e->item(0)->nodeValue;
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);
        $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);

        if ($errCode == 0) {
            //print("加密后: " . $encryptMsg . "\n");
            $xml = new \DOMDocument();
            $xml->loadXML($msg);
            /*$fp = fopen("/var/www/zjdaily/trunk/Public/Uploads/lottery/20180816/2.txt", "a");
            fwrite($fp, $msg . "\r\n");
            fclose($fp);*/
            $OpenWx = new WechatUserModel();
            $OpenWx->subscribe_relate($msg);//--将关注用户添加到数据库--
        } else {
//            $fp = fopen("/var/www/zjdaily/trunk/Public/Uploads/lottery/20180816/2.txt", "a");
//            fwrite($fp, $errCode . "\r\n");
//            fclose($fp);
        }
    }

    private function _curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    private function _curlPost($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "CURL post");
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function wxIndex()
    {
        $appid = 'wxdf4de6bcce43e4b5';
        $appsecret = 'fc1f811a8c7732d9a80589e11f78d726';
        $openid = session("gmm_openid");
        if ($openid) {
            echo $openid;
        } else {
            $wechat = new \Wap\Service\WechatService($appid, $appsecret);
            $url = $wechat->buildOauthURI("http://" . $_SERVER['HTTP_HOST'] . "/Home/OpenWx/wxEntry");
            redirect($url);
        }
    }

    public function wxEntry()
    {
        $appid = 'wxdf4de6bcce43e4b5';
        $appsecret = 'fc1f811a8c7732d9a80589e11f78d726';
        $code = I("get.code", "", "");
        $wechat = new \Wap\Service\WechatService($appid, $appsecret);
        $openid = $wechat->snsapiBaseUser($code);
        echo $openid;
    }
    public function test(){
        new WechatService('wx0b39dc9177895804', 'ef71bcb444898a47d0982200a76239ae');
        $access_token = S("wx0b39dc9177895804_access_token");
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
        $post['expire_seconds'] = 604800;
        $post['action_name'] = "QR_SCENE";
        $post['action_info'] = ["scene" => ["scene_str" => "test"]];
        $post = json_encode($post);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "CURL post");
        $ret = curl_exec($ch);
        curl_close($ch);
        $ret = json_decode($ret, true);
        var_dump($ret);
        if($ret['ticket']){
            $img = $this->_curlGet("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $ret['ticket']);
            echo $img;
        }
    }
}